﻿using UnityEngine;
using System.Collections;
using Engine.Entities.Character;
using System;

namespace FrenzyIsland.UI
{
    public class GuiManager : MonoBehaviour {

        public enum TypePlaceHolders
        {
            Building,
            Character
        }

        // Gameobject che contiene tutti i menu
        public GameObject menuPlaceHolders;
        public GameObject buildingPlaceHolders;
        public GameObject characterPlaceHolders;
        public delegate void SimpleDelegate();
        

        private GameObject openedWidget = null;
        private int contFollowTarget = 0;

        /// <summary>
        /// Apre un nuovo widget e copia il riferimento di quest'ultimo
        /// </summary>
        public GameObject openWidget(GameObject widget)
        {
            if (widget == null) return null;
            
            //chiudo il widget aperto
            if ( openedWidget != null)
            {
                NGUITools.Destroy(openedWidget);
            }

            //apro il nuovo widget
            GameObject newWidget = NGUITools.AddChild(menuPlaceHolders, widget);
            openedWidget = newWidget;

            newWidget.SetActive(true);

            return newWidget;
        }

        public void CloseWidget(GameObject widget)
        {
            NGUITools.Destroy(widget);
            openedWidget = null;
        }

        /// <summary>
        /// Apre un popup su una finestra
        /// Nel parent, verrà inserito il riferimento del nuovo popup
        /// Gui manager si preoccupa di istanziare la nuova finestra e di inserire i riferimenti nel parent
        /// </summary>
        /// <returns></returns>
        public GameObject openPopup(UIPopup parent, GameObject widget)
        {
            if (parent == null || widget == null) return null;

            //apro il nuovo widget usando come contenitore il gameobject del parent
            GameObject newWidget = NGUITools.AddChild(parent.gameObject, widget);
            parent.addChild(newWidget);
            newWidget.SetActive(true);
            return newWidget;
        }

        /// <summary>
        /// Apre una messagebox generica e gli assegna degli eventi generici
        /// Restituisce una message box generica che deve essere poi impostata da chi chiama questa funzione
        /// </summary>
        public UIMessageBox showMessageBox(
            UIPanel container, UIMessageBox msgBox, 
            SimpleDelegate okDelegate, SimpleDelegate cancelDelegate, 
            string message = null )
        {
            if (container == null) return null;

            GameObject objMsgBox = NGUITools.AddChild( container.gameObject, msgBox.gameObject );
            UIMessageBox msgBoxInstance = objMsgBox.GetComponent<UIMessageBox>();

            //imposto le proprietà per una message box standard
            msgBoxInstance.OkDelegate = okDelegate;
            msgBoxInstance.CancelDelegate = cancelDelegate;
            msgBoxInstance.Message = message;

            objMsgBox.SetActive(true);

            return msgBoxInstance;
        }

        internal GameObject AddFollowTarget(TypePlaceHolders type, GameObject prefab, GameObject target)
        {
            GameObject followTarget = null;
            GameObject container = null; 
            switch (type)
            {
                case TypePlaceHolders.Building:
                    container = buildingPlaceHolders;
                    break;
                case TypePlaceHolders.Character:
                    container = characterPlaceHolders;
                    break;
                default:
                    Debug.LogError("Tipo di placeholders non valido");
                    return null;
            }
            followTarget = NGUITools.AddChild(container, prefab);

            UIFollowTarget follower = followTarget.GetComponent<UIFollowTarget>();
            follower.gameCamera = Camera.main;
            follower.uiCamera = NGUITools.FindCameraForLayer(followTarget.layer);
            follower.target = target.transform;
            follower.enabled = true;

            //incremento il depth di tutti i figli (fix bug ui)
            IncreaseDepth(followTarget.transform); 
            contFollowTarget++;

            followTarget.SetActive(true);

            return followTarget;
        }

        private void IncreaseDepth(Transform parent)
        {
            parent.GetComponent<UIWidget>().depth += contFollowTarget;
            foreach (Transform t in parent.transform)
                IncreaseDepth(t);
        }

        internal Vector3 GetCenterPointScreen()
        {
            Transform tCam = Camera.main.transform;
            RaycastHit hit;
            Vector3 worldTCam = tCam.TransformDirection(Vector3.forward);
            if (Physics.Raycast(tCam.position, worldTCam, out hit))
            {
                return hit.point;
            }
            return Vector3.zero;
        }
    }
}


//   public GameObject MessageBox;
//   public FrenzyPeopleController peopleCtrl;
//   public CameraRigAction cameraRig;
//   public TerrainFirerController terrainFire;

//   [HideInInspector]
//   public delegate void SimpleDelegate();

//   private UIMessageBox MessageBoxOpened = null;

//   public bool IsAnyWindowOpened {
//       get {
//           return ActiveWindow != null;
//       }
//   }

//   public bool IsSelectedCharacterOpen
//   {
//       get { return false; } 
//   }

//   public GameObject SelectedCharacter { get; set; }

//   /// <summary>
//   /// Mantiene il riferimento alla finestra attualmente visualizzata
//   /// Blocca la telecamera quando imposto una nuova finestra
//   /// </summary>
//   public GameObject ActiveWindow {
//       get { return activeWindow; }
//       set
//       {
//           activeWindow = value;
//           if( value != null)
//           {
//               cameraRig.IsResponsive = false;
//               terrainFire.IsResponsive = false;
//           }
//           else
//           {
//               cameraRig.IsResponsive = true;
//               terrainFire.IsResponsive = true;
//           }
//       }
//   }
//   private GameObject activeWindow = null;

//void Start () {

//       //IsLocked = true;
//       //fix il bug della prima volta
//       //UICouple.SetActive(true);
//       //UICouple.transform.GetChild(0).gameObject.SetActive(false);
//       //UICouple.GetComponent<BoxCollider>().enabled = false;

//}

//   void Update()
//   {
//       // Nacondo il pannello informativo sulla sinistra...
//       if (Input.GetMouseButtonDown(0)) {

//           // ...Solo quando è aperto (ovviamente)...
//           //if (IsSelectedCharacterOpen)
//           if (false)
//           {

//               // ...e solo se ho colpito qualcosa che non è un personaggio
//               Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//               RaycastHit hit;
//               if (Physics.Raycast(ray, out hit))
//               {
//                   int layer = hit.collider.gameObject.layer;
//                   string name = LayerMask.LayerToName(layer);

//                   if (layer == 0)
//                   {
//                       HideSelectedCharacter();
//                   }
//               }
//           }
//       }

//       //procedura per far muovere la comitiva
//       //if (Input.GetMouseButtonDown(0))
//       //{
//       //    if (IsLocked)
//       //    {
//       //        //Debug.Log("aborted");
//       //        return;
//       //    }

//       //    PartyController partyController = _frenzyPeopleController.GetFirstPartyController();

//       //    RaycastHit hit;
//       //    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//       //    if (Physics.Raycast(ray, out hit))
//       //    {
//       //        Vector3 target = hit.point;
//       //        partyController.SetDestination(target);
//       //    }
//       //}

//}

//   public void CloseMenu(GameObject gameObject)
//   {
//       ActiveWindow = null;
//       Destroy(gameObject);
//   }

//   public GameObject OpenMenu(GameObject menu, AnchorMargin margin = null)
//   {
//       if (margin == null) margin = new AnchorMargin(50, 50, 50, 50);

//       GameObject instance = Instantiate(menu);

//       instance.transform.parent = this.transform;

//       //imposto la nuova finestra e blocco le telecamere ( setter )
//       ActiveWindow = instance;

//       instance.name = menu.name;
//       instance.SetActive(true);
//       instance.transform.localPosition = new Vector3(0, 0, 0);
//       instance.transform.localScale = new Vector3(1, 1, 1);

//       return instance;
//   }



//   //TODO Implementare il menu laterale con i prefab

//   private void ForceCloseGUI()
//   {
//       //ForceCloseSelectedCharacter();
//   }

//   /// <summary>
//   ///     Copia i riferimenti dell'oggetto cliccato
//   ///     Mostra la finestra del character selezionato
//   /// </summary>
//   /// <param name="gameObject">
//   ///     Item selezionato con il click
//   /// </param>
//   public void ShowSelectedCharacter(GameObject gameObject)
//   {
//       //if ( gameObject.name == "b4p3p")
//       //{
//       //    SteveModel model = gameObject.GetComponent<SteveBrain>().steveModel;
//       //    model.SetName("b4p3p", "odino");
//       //    model.Gender = GenderEnum.Male;
//       //}

//       //ActiveWindow = UISelectedCharacter;
//       //SelectedCharacter = gameObject;
//       //UISelectedCharacter.GetComponent<UISelectedCharacterCtrl>().Show(gameObject);
//   }

//   /// <summary>
//   /// - Nasconde il pannello laterale,
//   /// - Deleseleziona il Character selezionato
//   /// </summary>

//   public void HideSelectedCharacter()
//   {
//       //UISelectedCharacter.GetComponent<UISelectedCharacterCtrl>().Hide();

//       //ItemMouseAction ima = SelectedCharacter.GetComponent<ItemMouseAction>();
//       //if (ima)ima.Unselect();

//       //ActiveWindow = null;
//       //SelectedCharacter = null;
//   }

//   public void ForceCloseSelectedCharacter()
//   {
//       //UISelectedCharacter.GetComponent<UISelectedCharacterCtrl>().ForceClose();
//   }

//   public void ShowMessageBox(string message, SimpleDelegate yesDelegate, SimpleDelegate noDelegate)
//   {
//       GameObject objMsgBox = Instantiate(MessageBox);
//       objMsgBox.transform.parent = this.transform;
//       objMsgBox.transform.localScale = new Vector3(1, 1, 1);
//       objMsgBox.transform.localPosition = new Vector3(0,0,0);

//       UIMessageBox msg = UIMessageBox.SetComponent(objMsgBox, message, yesDelegate, noDelegate);

//       MessageBoxOpened = msg;
//   }


//public void ShowMenuBuilding()
//        {
//            UIBuildings.SetActive(true);
//            ActiveWindow = UIBuildings;
//        }

//        public void ShowMenuParty()
//        {
//            UIParty.SetActive(true);
//            ActiveWindow = UIParty;
//            UIParty.GetComponent<UIPartyCtrl>().LoadParty();
//        }


//public void NewIslandClick()
//{
//    //Debug.Log("Click new island");
//    //Destroy(World);
//    //World = Instantiate(WorldPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
//    //World.name = "VoxelWorld";
//    //RefreshGuiManager();
//}

//public void ShowMenuCouple()
//{
//    //necessario impostare il panel per evitare il bug di NGUI
//    //UICouple.SetActive(true);
//    //UICouple.transform.GetChild(0).gameObject.SetActive(true);
//    //ActiveWindow = UICouple;

//    //_coupleManager.LoadPeople();
//}


//private void SetMargin(AnchorMargin margin, GameObject obj, Transform parent)
//{
//    UIWidget widget = obj.GetComponent<UIWidget>();

//    Debug.Assert(widget != null, "Widget is null");

//    widget.leftAnchor.target = parent;
//    widget.leftAnchor.absolute = margin.left;

//    widget.rightAnchor.target = parent;
//    widget.rightAnchor.absolute = margin.right * -1;

//    widget.bottomAnchor.target = parent;
//    widget.bottomAnchor.absolute = margin.bottom;

//    widget.topAnchor.target = parent;
//    widget.topAnchor.absolute = margin.top * -1;

//    widget.UpdateAnchors();
//}